package com.duoec.magichour.service.impl;

import com.duoec.magichour.enums.SmsMessageTypeEnum;
import com.duoec.magichour.invoker.SmsInvoker;
import com.duoec.magichour.mapper.SmsMapper;
import com.duoec.magichour.pojo.Sms;
import com.duoec.magichour.service.SmsService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;

import java.util.Calendar;
import java.util.Date;
import java.util.Random;

/**
 * Created by ycoe on 17/7/4.
 */
@Service
public class SmsServiceImpl implements SmsService {
    @Autowired
    private SmsMapper smsMapper;

    @Value("${sms.code.expire}")
    private int mobileCodeExpireTime;

    @Value("${sms.resetPwd.expire}")
    private int resetPwdExpireTime;

    @Autowired
    private SmsInvoker smsInvoker;

    @Override
    public String getCode(String mobile) {
        Sms sms = getByMobileType(mobile, SmsMessageTypeEnum.MOBILE_CODE);

        if (sms == null) {
            //需要创建
            //生成验证码
            int code = 1000 + new Random().nextInt(8999);

            sms = new Sms();
            sms.setCode(String.valueOf(code));
            sms.setCreateTime(new Date());
            sms.setErrorCount(0);
            sms.setMessage("");
            sms.setMessageType(SmsMessageTypeEnum.MOBILE_CODE.getCode());
            sms.setMobile(mobile);
            smsMapper.insertSelective(sms);

        }
//        smsInvoker.send(sms);
        return "验证码已发送，请注意查收！";
    }

    @Override
    public String resetMobilePwd(String mobile, String pwd) {
        Sms sms = getByMobileType(mobile, SmsMessageTypeEnum.RESET_PWD);

        if (sms == null) {
            //需要创建
            sms = new Sms();
            sms.setCode(pwd);
            sms.setCreateTime(new Date());
            sms.setErrorCount(0);
            sms.setMessage("");
            sms.setMessageType(SmsMessageTypeEnum.RESET_PWD.getCode());
            sms.setMobile(mobile);
            smsMapper.insertSelective(sms);
        }
        smsInvoker.send(sms);
        return "密码已发送到指定手机，请注意查收！";
    }

    @Override
    public Sms getByMobileType(String mobile, SmsMessageTypeEnum messageType) {
        Calendar calendar = Calendar.getInstance();
        calendar.add(Calendar.MINUTE, -getExpireTime(messageType));
        return smsMapper.getByType(mobile, messageType.getCode(), calendar.getTime());
    }

    @Override
    public void incErrorCount(Long id) {
        smsMapper.incErrorCount(id);
    }

    @Override
    public void used(Long id) {
        smsMapper.used(id);
    }

    public int getExpireTime(SmsMessageTypeEnum messageType) {
        switch (messageType) {
            case MOBILE_CODE:
                return mobileCodeExpireTime;
            case RESET_PWD:
                return resetPwdExpireTime;
            default:
                return 30;
        }
    }
}
